package com.pmcc.yn.service;

import com.pmcc.utils.*;
import com.pmcc.yn.entity.*;
import com.pmcc.yn.repository.*;
import com.pmcc.yn.vo.OrderListTechVo;
import com.pmcc.yn.vo.OrderListVo;
import com.pmcc.yn.vo.StoreInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by yaonan on 2019/1/10.
 */
@Service
@Transactional
public class StoreInfoService {

     @Autowired
    StoreInfoRepository repository;

    @Autowired
    EntryInfoRepository entryInfoRepository;

    @Autowired
    TechnicianInfoRepository technicianInfoRepository;

    @Autowired
    OrderListRepository orderListRepository;

    @Autowired
    AcceptInfoRepository acceptInfoRepository;

    @Autowired
    EvaluateInfoRepository evaluateInfoRepository;

    @Autowired
    AttentionInfoRepository attentionInfoRepository;

    @Value("${web.downloadFile}")
    private  String downloadFile;

    public ResultBean showList(AntdPage antdPage , StoreInfo model) throws Exception{
        ResultBean resultBean=new ResultBean();
        Page page=repository.findAll(this.getSpecification(model),antdPage.getPageRequest());

        resultBean.setPage(antdPage.getDefaultCurrent());
        resultBean.setTotal(page.getTotalElements());
        resultBean.setResultCode(ResultBean.SUCCESS);
        resultBean.setPageSize(antdPage.getPageSize());
        resultBean.setRows(page.getContent());
        return resultBean;
    }

    public Specification<StoreInfo> getSpecification(StoreInfo model) {
        return new Specification<StoreInfo>() {
            @Override
            public Predicate toPredicate(Root<StoreInfo> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
                List<Predicate> list = new ArrayList<Predicate>();
                if(model.getFlag()!=null){
                    list.add(builder.equal(root.get("flag").as(Integer.class),model.getFlag()));
                }

                Predicate[] p = new Predicate[list.size()];
                return builder.and(list.toArray(p));
            }
        };
    }

    /**
     * 新增
     * @return
     */
    public ResultBean add(StoreInfo model){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try{
            model.setCreateTime(new Date());
            model.setFlag(0);
            repository.saveAndFlush(model);
            resultBean.setResultCode(ResultBean.SUCCESS);
            resultBean.setResultDesc("新增成功");
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }



    /**
     * 修改
     * @param map
     * @return
     */
    public ResultBean update(Map map) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            StoreInfo c = repository.findById(map.get("id").toString());
            BeanUtils.setBeanData(c,map);
            repository.saveAndFlush(c);
            resultBean.setResultCode(ResultBean.SUCCESS);
            resultBean.setObject(c);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    /**
     * 删除
     * @param id
     * @return
     */
    public ResultBean deleteById(String id) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            StoreInfo f = repository.findById(id);
            f.setFlag(1);
            repository.saveAndFlush(f);
            resultBean.setResultCode(ResultBean.SUCCESS);
            resultBean.setObject(f);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }


    public ResultBean supplementPhoto(MultipartFile file, String mid, String type) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        // 上传的文件存放路径
        String uploadDiskPath = downloadFile;
        if (!file.isEmpty()) {
            try {
                String originalFilename = new String(file.getOriginalFilename());
                String[] arr = originalFilename.split("\\.");
                // 文件类型
                String fileType = arr.length > 1 ? arr[arr.length - 1] : "";
                // 存放在服务器端的文件名
                String serverFileName = fileType == "" ? UUIDGenerator.getUUID() : UUIDGenerator.getUUID() + "." + fileType;
                // 创建文件夹  年-月-日/goods
                String folder = "/" + DateUtil.DateToString(new Timestamp(new Date().getTime()), "yyyy-MM-dd");
                // 数据库存放路径：年-月-日/文件名
                String fileUrl = "/" + folder + "/" + serverFileName;


                File targetFile = new File(uploadDiskPath, fileUrl);
                if (!targetFile.exists()) {
                    targetFile.getParentFile().mkdir();
                    targetFile.createNewFile();
                }
                file.transferTo(targetFile);
            } catch (FileNotFoundException e) {
                e.printStackTrace();

            } catch (IOException e) {
                e.printStackTrace();

            }

        } else {

        }

        return  resultBean;
    }

    /**
     * 根据id 查询门店详情
     * @param id
     * @return
     */
    public  StoreInfo findDetailById(String id){
        StoreInfo storeInfo = new StoreInfo();
        storeInfo = repository.getOne(id);
        return storeInfo;
    }
    /**
     * 移动端传入wxid，先判断在该wxid是否在门店表中存在，如果存在则允许登录，返回门店的id和已经门店的基本信息，
     * 如果不存在则新增一条门店记录。同样返回门店的基本信息，在resultDesc里面要求填写是新创建的门店
     *
     */
    public ResultBean login(String wxid) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            StoreInfo storeInfo = repository.findById(wxid);
            if (storeInfo!= null) {
                resultBean.setResultCode(ResultBean.SUCCESS);
                resultBean.setObject(storeInfo);
            } else {
                StoreInfo s = new StoreInfo();
                s.setWxId(wxid);
                repository.saveAndFlush(s);
                resultBean.setObject(s);
                resultBean.setResultDesc("新创建门店");
            }
        }catch(Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
   /*
    * 门店接单状态
    *
    * */
    public ResultBean orderStatus(String id) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try{
            List<OrderList> orderLists = orderListRepository.findByStoreId(id);
            List<OrderListVo> list = new ArrayList<>();
            for (OrderList orderList:orderLists){
//                orderListVo.setVeh_imageurl(orderList.getVehPicl());
//                orderListVo.setVehModel(orderList.getVehModel());
//                orderListVo.setSerType(orderList.getSerType());
//                orderListVo.setPreTime(orderList.getPreTime());
//                orderListVo.setMoney(orderList.getMoney());
//                orderListVo.setEntryNum(orderList.getEntryNum());
//                orderListVo.setFlag(orderList.getFlag());
                OrderListVo vo=new OrderListVo();
                vo.setVehModel(orderList.getVehModel());
                vo.setVehImageurl(orderList.getVehPicl());
                vo.setSerType(orderList.getSerType());
                vo.setPreTime(orderList.getPreTime());
                vo.setMoney(orderList.getMoney());
                //查询出某个订单下的关注数量
                List<AttentionInfo> attentionInfos=attentionInfoRepository.findByOrderId(orderList.getId());
                vo.setAttemNum(attentionInfos.size());
                vo.setFlag(orderList.getFlag());
                List<OrderListTechVo> techs=new ArrayList<>();

                if(vo.getFlag()==1){
                    //该订单有多少个技师做了报名
                    List<EntryInfo>  entryInfos=entryInfoRepository.findByOrderIdAndDelFlag(orderList.getId(),0);
                    for(EntryInfo ei:entryInfos){
                        TechnicianInfo ti=technicianInfoRepository.findById(ei.getTechnicianId());
                        OrderListTechVo ov=new OrderListTechVo(ti.getId(),ti.getName(),ti.getImageurl());
                        techs.add(ov);
                    }
                    vo.setEntryNum(entryInfos.size());

                }else if(vo.getFlag()==2){
                    TechnicianInfo ti=technicianInfoRepository.findById(orderList.getTechId());
                    OrderListTechVo ov=new OrderListTechVo(ti.getId(),ti.getName(),ti.getImageurl());
                    techs.add(ov);
                }
                vo.setTechvolist(techs);
                list.add(vo);
            }
           // resultBean.setObject(orderListVo);
            resultBean.setRows(list);
        }catch(Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    //评价图片上传
    public String assessPhoto(MultipartFile file) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        // 上传的文件存放路径
        String uploadDiskPath = downloadFile;
        String employeeID;
        if (!file.isEmpty()) {
            try {
                String originalFilename = new String(file.getOriginalFilename());
                String[] arr = originalFilename.split("\\.");
                // 文件类型
                String fileType = arr.length > 1 ? arr[arr.length - 1] : "";
                // 存放在服务器端的文件名
                String serverFileName = fileType == "" ? UUIDGenerator.getUUID() : UUIDGenerator.getUUID() + "." + fileType;
                // 创建文件夹  年-月-日/goods
                String folder = "/" + DateUtil.DateToString(new Timestamp(new Date().getTime()), "yyyy-MM-dd");
                // 数据库存放路径：年-月-日/文件名
                String fileUrl = "/" + folder + "/" + serverFileName;

//            OrderList c = repository.findById(id);
////                c.setPhoto("/downloadFile"+fileUrl);
//            repository.saveAndFlush(c);
                File targetFile = new File(uploadDiskPath, fileUrl);
                if (!targetFile.exists()) {
                    targetFile.getParentFile().mkdir();
                    targetFile.createNewFile();
                }
                file.transferTo(targetFile);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return "上传失败," + e.getMessage();
            } catch (IOException e) {
                e.printStackTrace();
                return "上传失败," + e.getMessage();
            }
            return "上传成功";
        } else {
            return "上传失败，因为文件是空的.";
        }
    }
    //发表评价
    public ResultBean addAssess(String id, String score, String assess, MultipartFile file) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            EvaluateInfo evaluateInfo = new EvaluateInfo();
            evaluateInfo.setOrderId(id);
            evaluateInfo.setScore(Double.valueOf(score));
            evaluateInfo.setCommentContent(assess);
            evaluateInfo.setPicAddress1(this.assessPhoto(file));
            evaluateInfoRepository.saveAndFlush(evaluateInfo);
            resultBean.setObject(evaluateInfo);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    //门店个人中心
    public ResultBean storeCenter(String id) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            StoreInfo storeInfo = repository.findById(id);
            StoreInfoVo storeInfoVo = new StoreInfoVo();
            storeInfoVo.setName(storeInfo.getName());
            storeInfoVo.setPhoto1(storeInfo.getPhoto1());
            storeInfoVo.setAddress(storeInfo.getAddress());
            storeInfoVo.setLeader(storeInfo.getLeader());
            storeInfoVo.setPhone(storeInfo.getPhone());
          //  resultBean.setObject(storeInfoVo);
            List<OrderList> orderLists = orderListRepository.findByStoreIdOrderByCreateTimeDesc(id);
            List<OrderListVo> olvs=new ArrayList<>();

            for (OrderList orderList:orderLists) {
                OrderListVo orderListVo= new OrderListVo();
                orderListVo.setSerType(orderList.getSerType());
                orderListVo.setPreTime(orderList.getPreTime());
                orderListVo.setMoney(orderList.getMoney());
                TechnicianInfo technicianInfo = technicianInfoRepository.findById(orderList.getTechId());
               // orderListVo.setTechName(technicianInfo.getName());
                orderListVo.setTechName(technicianInfo.getName());
                olvs.add(orderListVo);
            }
            storeInfoVo.setOrds(olvs);
            resultBean.setObject(storeInfoVo);
         //   resultBean.setObject(orderListVo);
           // resultBean.setObject(techInfoVo);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    //门店个人中心（编辑）
    public ResultBean storeById(String id) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            StoreInfo storeInfo = repository.findById(id);
            StoreInfoVo storeInfoVo = new StoreInfoVo();
            storeInfoVo.setPhoto1(storeInfo.getPhoto1());
            storeInfoVo.setName(storeInfo.getName());
            storeInfoVo.setPhone(storeInfo.getPhone());
            storeInfoVo.setLeader(storeInfo.getLeader());
            storeInfoVo.setAddress(storeInfo.getAddress());
            resultBean.setObject(storeInfoVo);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    //修改保存个人信息
    public ResultBean updateStore(StoreInfo storeInfo){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            StoreInfo storeInfo1 = repository.findById(storeInfo.getId());
            repository.saveAndFlush(storeInfo1);
            resultBean.setResultCode(ResultBean.SUCCESS);
            resultBean.setObject(storeInfo1);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
}
